"""
刷新景点数据：批量获取各类别景点完整数据（包括图片）
"""
import time
from django.core.management.base import BaseCommand
from django.conf import settings
from apps.attractions.models import Attraction
from utils.amap_client import AMapClient
from decimal import Decimal


class Command(BaseCommand):
    help = '刷新景点数据：批量获取各类别景点完整数据（包括图片）'

    # 各类别的搜索关键词
    CATEGORY_KEYWORDS = {
        'cultural': ['博物馆', '纪念馆', '古迹', '遗址', '古建筑', '文化馆', '历史建筑', '文物', '古塔'],
        'natural': ['公园', '风景区', '湖泊', '山', '自然', '生态', '湿地', '森林公园', '植物园'],
        'modern': ['科技馆', '展览馆', '地标', '现代建筑', '广场', '商业中心', '摩天轮', '观景台'],
        'food': ['美食街', '小吃街', '购物街', '商业街', '美食广场', '夜市', '步行街']
    }

    def add_arguments(self, parser):
        parser.add_argument(
            '--category',
            type=str,
            choices=['cultural', 'natural', 'modern', 'food', 'all'],
            default='all',
            help='要获取的类别'
        )
        parser.add_argument(
            '--location',
            type=str,
            default='115.89,28.68',
            help='中心点坐标（经度,纬度）'
        )
        parser.add_argument(
            '--radius',
            type=int,
            default=50000,
            help='搜索半径（米）'
        )
        parser.add_argument(
            '--max-per-category',
            type=int,
            default=20,
            help='每个类别最大数量'
        )
        parser.add_argument(
            '--update-existing',
            action='store_true',
            help='更新已存在的景点'
        )

    def handle(self, *args, **options):
        api_key = settings.AMAP_CONFIG.get('API_KEY')
        if not api_key or api_key == 'your_amap_api_key':
            self.stdout.write(self.style.ERROR('❌ 高德地图API Key未配置！'))
            return

        amap_client = AMapClient(api_key)
        category = options['category']
        location = options['location']
        radius = options['radius']
        max_per_category = options['max_per_category']
        update_existing = options['update_existing']

        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('开始刷新景点数据'))
        self.stdout.write(self.style.SUCCESS('=' * 60))

        categories = ['cultural', 'natural', 'modern', 'food'] if category == 'all' else [category]
        
        total_created = 0
        total_updated = 0
        total_images = 0

        for cat in categories:
            self.stdout.write(f'\n处理类别: {cat}')
            self.stdout.write('-' * 60)
            
            keywords = self.CATEGORY_KEYWORDS[cat]
            all_pois = []
            
            # 搜索POI
            for keyword in keywords:
                if len(all_pois) >= max_per_category:
                    break
                    
                page = 1
                while len(all_pois) < max_per_category:
                    try:
                        result = amap_client.search_pois_by_location(
                            location=location,
                            keywords=keyword,
                            types='风景名胜|公园广场|博物馆|纪念馆',
                            radius=radius,
                            page=page,
                            page_size=20
                        )
                        
                        if result.get('status') != '1':
                            break
                            
                        pois = result.get('pois', [])
                        if not pois:
                            break
                        
                        # 去重
                        existing_ids = {p.get('id') for p in all_pois}
                        new_pois = [p for p in pois if p.get('id') not in existing_ids]
                        all_pois.extend(new_pois)
                        
                        if len(pois) < 20:
                            break
                            
                        page += 1
                        time.sleep(0.3)
                    except Exception as e:
                        self.stdout.write(f'  搜索失败: {str(e)}')
                        break
            
            all_pois = all_pois[:max_per_category]
            self.stdout.write(f'找到 {len(all_pois)} 个POI\n')
            
            # 处理每个POI
            for idx, poi in enumerate(all_pois, 1):
                try:
                    poi_id = poi.get('id', '')
                    poi_name = poi.get('name', '')
                    location_str = poi.get('location', '')
                    
                    if not location_str:
                        continue
                    
                    loc_parts = location_str.split(',')
                    if len(loc_parts) < 2:
                        continue
                    
                    longitude = Decimal(loc_parts[0])
                    latitude = Decimal(loc_parts[1])
                    address = poi.get('address', '')
                    
                    self.stdout.write(f'[{idx}/{len(all_pois)}] {poi_name}')
                    
                    # 获取POI详情和图片
                    image_urls = []
                    description = poi.get('intro', '')
                    rating = 4.0
                    ticket_price = Decimal('0.00')
                    
                    if poi_id:
                        try:
                            time.sleep(0.3)
                            poi_detail = amap_client.get_poi_detail(poi_id)
                            
                            if poi_detail.get('status') == '1' and poi_detail.get('pois'):
                                poi_data = poi_detail['pois'][0]
                                
                                # 提取图片
                                photos = poi_data.get('photos', [])
                                for photo in photos[:10]:
                                    if isinstance(photo, dict):
                                        url = photo.get('url') or photo.get('src', '')
                                        if url:
                                            if not url.startswith('http'):
                                                url = 'https://restapi.amap.com' + url if url.startswith('/') else url
                                            image_urls.append(url)
                                    elif isinstance(photo, str) and photo.startswith('http'):
                                        image_urls.append(photo)
                                
                                # 提取描述
                                if poi_data.get('intro'):
                                    description = poi_data.get('intro')
                                
                                # 提取评分
                                rating_str = poi_data.get('rating', '')
                                if rating_str:
                                    try:
                                        rating = float(rating_str)
                                    except:
                                        pass
                                
                                # 提取价格
                                cost = poi_data.get('cost', '')
                                if cost:
                                    import re
                                    match = re.search(r'(\d+\.?\d*)', cost)
                                    if match:
                                        try:
                                            ticket_price = Decimal(match.group(1))
                                        except:
                                            pass
                                
                                if image_urls:
                                    self.stdout.write(f'  ✓ 获取 {len(image_urls)} 张图片')
                        except Exception as e:
                            self.stdout.write(f'  ⚠ 获取详情失败: {str(e)}')
                    
                    popularity = int(rating * 20)
                    
                    # 创建或更新景点
                    attraction, created = Attraction.objects.get_or_create(
                        amap_poi_id=poi_id,
                        defaults={
                            'name': poi_name,
                            'latitude': latitude,
                            'longitude': longitude,
                            'address': address,
                            'description': description,
                            'category': cat,
                            'ticket_price': ticket_price,
                            'popularity': popularity,
                            'rating': rating,
                            'amap_image_urls': image_urls,
                        }
                    )
                    
                    if created:
                        total_created += 1
                        self.stdout.write(self.style.SUCCESS(f'  ✓ 创建成功'))
                    elif update_existing:
                        attraction.name = poi_name
                        attraction.latitude = latitude
                        attraction.longitude = longitude
                        attraction.address = address
                        attraction.description = description
                        attraction.category = cat
                        attraction.ticket_price = ticket_price
                        attraction.popularity = popularity
                        attraction.rating = rating
                        if image_urls:
                            attraction.amap_image_urls = image_urls
                        attraction.save()
                        total_updated += 1
                        self.stdout.write(self.style.SUCCESS(f'  ↻ 更新成功'))
                    else:
                        self.stdout.write(self.style.WARNING(f'  - 已存在'))
                    
                    total_images += len(image_urls)
                    
                except Exception as e:
                    self.stdout.write(self.style.ERROR(f'  ✗ 失败: {str(e)}'))
        
        self.stdout.write('\n' + '=' * 60)
        self.stdout.write(self.style.SUCCESS('完成！'))
        self.stdout.write('=' * 60)
        self.stdout.write(f'创建: {total_created} 个')
        self.stdout.write(f'更新: {total_updated} 个')
        self.stdout.write(f'图片: {total_images} 张')

